package com.yilin.tms.core.application;

import com.google.gson.reflect.TypeToken;
import com.yilin.commons.encrypt.EncryptUtils;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.HttpService;
import com.yilin.commons.util.JsonUtil;
import com.yilin.commons.util.MapUtil;
import com.yilin.commons.util.StringUtil;
import java.util.HashMap;
import java.util.Map;

public class PlatRequest {

    // 模拟请求 POST 平台地址 自动调用网关地址
    public static <T> T request( String apiToken, String url,Map<String,Object> param,TypeToken<T> typeToken){
        String body = JsonUtil.objectToJson(param);
        Map<String,String> header = new HashMap<>();
        String encrypt = EncryptUtils.aesEncrypt(body, apiToken);
        Map<String,Object> map = new HashMap<>();
        map.put("body",encrypt);
        header.put("token", apiToken);
        String result = HttpService.httpPostWithJson(url, JsonUtil.objectToJson(map),header);
        ReturnData<T> returnData = JsonUtil.jsonToObject(result, new TypeToken<ReturnData<T>>(){});
        if (returnData==null) throw new BusinessException("请求返回为空");
        if (!returnData.isSuccess()) throw new BusinessException(returnData.getMsg());
        if (returnData.getToken() != null) apiToken = returnData.getToken();
        if (StringUtil.isEmpty(returnData.getEncData())) return null;
        String resultJson = EncryptUtils.aesDecrypt(returnData.getEncData(), apiToken);
        T t;
        try {
             t=  JsonUtil.jsonToObject(resultJson, typeToken);
        } catch (Exception e) {
           return (T) resultJson;
        }
        return t;
    }

    public static void main(String[] args) {
        String  ss="/KdWkdm/FugcoEIzv/VdFPoPqZi7BmAX2TPel4c4Rp3jCHK/JiswLnA159YXqgcrZOjQUGcXZHksGVfWvVDmHAEGmdNjJs8gcOuVwQw2HsR4/sI/AvE+iucVND9/eu3TYMZqEChUQIv0jPqfTsKkAsx4zAR2OF75qjRH29wFHDCqGKgw0heu+3IicjKMgtquIFb+BLxQttt0peGbrWSEjFDn6OdOre+aP5e0UXtv9oGOGrLWDcMZTAK0C8EpicpyizLxsFv8yf16CJ/O5VqYxoNs1BPi+V3ab8Ojlrtc8dtoeKzQBkQE7djmw/6LxOQUn4DynSlbSXYAKhlhITcJsb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APe6/HEk7UwH5vnREgpRCIIoDiosJIAaYogh4kyczPdnZDHsM35yEu/kVstfYAlblmDAzaGCeUngbH/pC2JVo6ejUDmjK3emoiaIvEhO2yGXUd1USAleX1gvy9p04z0CHyQbRpIydAMHcJViJye+g2ylACgO0MXjs6cuKurdCgRW43O8JsaSxKqo4cYVUqXjgcWnQUoGLUaqIoqwvqBo3dIkBRJaPijjUmQiY=";
        Object cmb=EncryptUtils.aesDecrypt(ss, null);
        System.out.println();
    }

    //模拟请求 GET 平台地址 自动调用网关地址
    public static String selfGet(String apiToken, String path, Map<String,Object> param){
        Map<String,String> header = MapUtil.generate(map -> map.put("token", apiToken));
        return HttpService.doGet(AppUtil.getZuulPath() + path, param, header);
    }
}
